package org.smartboot.socket.common;

import org.smartboot.socket.Protocol;
import org.smartboot.socket.common.ChatMessage;
import org.smartboot.socket.transport.AioSession;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.nio.ByteBuffer;
/**传输过来的消息byte流，如何转换成你要的对象。。。
 * @author laoliu
 * @since 1.0
 */
public class ChatProtocal implements Protocol<ChatMessage> {
    @Override
    public ChatMessage decode(ByteBuffer readBuffer, AioSession session) {
        if( readBuffer.remaining()<Integer.BYTES)
        {
            return null;
        }
        readBuffer.mark();
        int length=readBuffer.getInt();
        if(length>readBuffer.remaining())
        {
            readBuffer.reset();
            return null;
        }

       // System.out.println(length+">>>>>>>>>>>>>>");

        byte[]b=new byte[length];
        readBuffer.get(b);
        readBuffer.mark();
        try {
            ObjectInputStream oin=new ObjectInputStream(new ByteArrayInputStream(b));
            ChatMessage m=(ChatMessage)oin.readObject();
            oin.close();
            return m;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
